<script setup>
import {onMounted, ref, watch} from 'vue'
import axios from "axios";
import {queryPageEmpsApi, addEmpApi, updateByIdApi, queryEmpByIdApi,deleteByIDApi} from "@/api/emp.js";
import { queryAllDeptsApi} from "@/api/dept.js";
import {ElMessage, ElMessageBox} from "element-plus";

//token
const token=ref('')

const getToken=()=>{
  const loginUser=JSON.parse(localStorage.getItem('loginUser'))
  if(loginUser&&loginUser.token){
    token.value=loginUser.token
  }
}
//数据准备
const jobs=ref(
    [
      {name:'班主任', value:1},
      {name:'讲师', value:2},
      {name:'学工主管', value:3},
      {name:'教研主管', value:4},
      {name:'咨询师', value:5},
      {name:'其他',value:6}
    ]
)
const depts=ref([])

const emp=ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})
const empList=ref([])
const searchEmp=ref({
  name:'',
  gender:'',
  date:[],
  begin:'',
  end:''
})

const searchDepts=async ()=>{
  const result=await queryAllDeptsApi()
  if(result.code){
    depts.value=result.data
  }
}
const onSearch=async ()=>{
  const result= await queryPageEmpsApi(searchEmp.value.name,searchEmp.value.gender,
      searchEmp.value.begin,searchEmp.value.end,currentPage.value,pageSize.value)
  if(result.code){
    empList.value=result.data.rows
    total.value=result.data.total
  }
}
const onClear=()=>{
  searchEmp.value={
    name:'',
    gender:'',
    date:[],
    begin:'',
    end:''
  }
  onSearch()
}

//新增按钮绑定的方法
const add=()=>{
  dialogFormVisible.value=true
  formTitle.value='新增员工'
  emp.value={
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }
  if(formRef.value){
    formRef.value.resetFields()
  }
}
const formRef=ref()
//保存员工信息
const save=async ()=>{
    formRef.value.validate(async (valid)=>{
    if(valid){

      let result
      if(emp.value.id){
        result=await updateByIdApi(emp.value)
      } else{
        result=await addEmpApi(emp.value)
      }

      if(result.code){
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        dialogFormVisible.value=false
        onSearch()
      }else{
        ElMessage.error('操作失败，员工已存在')
      }
    }else{
      ElMessage.error('表单校验不通过')
    }
  })
}
//修改员工信息的脚本
const edit=async (id)=>{

  formTitle.value='编辑员工信息'
  const result=await queryEmpByIdApi(id)
  console.log(result.data)
  if(1) {
    dialogFormVisible.value = true
    emp.value = result.data

    let exprList=emp.value.exprList
    if(exprList&&exprList.length>0){
      exprList.forEach((expr)=>{
          expr.exprDate=[expr.begin,expr.end]
        }
      )
    }
  }
}
//根据id删除员工信息
const ids=ref([])
const handleSelectionChange=(value)=>{
  //将每个元素的id封装到一个新数组中
  ids.value= value.map(item=>item.id)
}
const deleteByIDs=()=>{
  ElMessageBox.confirm('您确认要删除员工信息吗','提示',
  {
    confirmButtonText:'确认',cancelButtonText:'取消',type:'warning'
  }
  ).then(async ()=>{
    const result=await deleteByIDApi(ids.value)
    if(result.code){
      ElMessage.success('删除成功')
      onSearch()
    }else{
      ElMessage.error(result.msg)
    }
  }).catch(()=>{
    ElMessage.info('您已取消删除')
  })

}

const deleteByID=(id)=>{
  ElMessageBox.confirm('您确认要删除员工信息吗','提示',
      {
        confirmButtonText:'确认',cancelButtonText:'取消',type:'warning'
      }
  ).then(async ()=>{
    const result=await deleteByIDApi(id)
    if(result.code){
      ElMessage.success('删除成功')
      onSearch()
    }else{
      ElMessage.error(result.msg)
    }
  }).catch(()=>{
    ElMessage.info('您已取消删除')
  })

}



//处理工作经历的增删，围绕数据做操作，通过vue的双向绑定可以实现数据的动态显示
const addExprItem=()=>{
  emp.value.exprList.push({
    company:'',
    job:'',
    begin:'',
    end:'',
    exprDate:[]
  })
}
const deleteExprItem=(index)=>{
  emp.value.exprList.splice(index,1)
}
//校验规则
const rules = ref({
  username: [
    { required: true, message: '用户名必填', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度须在2到20位', trigger: 'blur' },
  ],
  name:[
    {
      required:true,message:'姓名必填',trigger:'blur'
    },
    {
      min:2,max:10,message:'姓名长度须在2到20位',trigger:'blur'
    }
  ],
  gender:[
    {
      required:true,message:'性别必选',trigger:'change'
    }
  ],
  phone:[
      //注意正则表达式的写法
    { required: true, message: '手机号必填', trigger: 'blur' },
    {pattern:/^1[3-9]\d{9}$/,message:'请输入有效的手机号',trigger:'blur'}
  ]
})


//分页相关
const currentPage = ref(1) //页码
const pageSize = ref(50) //每页默认记录数
const background = ref(true)
const total=ref(1000) //总记录数

const handleSizeChange = (val) => {
  console.log(`每页记录数为${val}`)
  onSearch()
}
const handleCurrentChange = (val) => {
  console.log(`当前页码为${val}`)
  onSearch()
}

// watch 侦听：
//1. 设置一个事件源，监听事件源的变化来做出某种响应
//2. 深度侦听：侦听一个对象的变化。
//3. 侦听对象某一个属性

watch(()=>{return searchEmp.value.date},(newVal,oldVal)=>{
  if(newVal.length==2){
    searchEmp.value.begin=newVal[0]
    searchEmp.value.end=newVal[1]
  }else{
    searchEmp.value.begin=''
    searchEmp.value.end=''
  }
})

//对话框相关脚本
const dialogFormVisible=ref(false)
const formTitle=ref('')
  //文件上传
const handleAvatarSuccess=(response)=>{
  emp.value.image=response.data
  console.log(response)
}
  //文件上传之前对文件的检验
const beforeAvatarUpload=(rawFile)=>{
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('必须是图片jpg文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不得超过2MB!')
    return false
  }
  return true
}


//侦听员工对象中的工作经历
watch(()=>emp.value.exprList,(newVal,oldVal)=>{
  //在员工工作经历存在有效数据的情况下，为工作经历的开始日期和结束日期赋值
  if(emp.value.exprList&&emp.value.exprList.length>0){
    //遍历员工的工作经历，分别复制
    emp.value.exprList.forEach((expr)=>{
      expr.begin=expr.exprDate[0]
      expr.end=expr.exprDate[1]
      }
    )
  }
})



onMounted(()=>{
  onSearch()
  searchDepts()
  getToken()
})

</script>

<template>
  <h1 id="title">员工管理</h1>
<!--  <div id="btn-container">-->
<!--    <el-button type="primary" @click="addEmp"><el-icon><Plus /></el-icon>新增员工</el-button>-->
<!--    <el-button type="primary" @click="deleteEmpBatch"><el-icon><Delete /></el-icon> 批量删除</el-button>-->
<!--  </div>-->
  <div id="search">
    <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchEmp.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="性别">
        <el-select
            v-model="searchEmp.gender"
            placeholder="请选择性别"
            clearable
        >
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期">
        <div class="block">
          <el-date-picker
              v-model="searchEmp.date"
              type="daterange"
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="info" @click="onClear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-button type="primary" @click="add"><el-icon><Plus /></el-icon>新增员工</el-button>
  <el-button type="danger"  @click="deleteByIDs"><el-icon><Delete /></el-icon>批量删除</el-button>
  <div id="table-container">
    <el-table :data="empList" border style="width: 100%"  @selection-change="handleSelectionChange">
      <el-table-column type="selection"  width="55" align="center"/>
      <el-table-column prop="name" label="姓名" width="120" align="center"/>
      <el-table-column prop="gender" label="性别" width="120" align="center">
        <template #default="scope">
          {{scope.row.gender==1?'男':'女'}}
        </template>
      </el-table-column>
      <el-table-column prop="image" label="头像" width="120" align="center">
        <template #default="scope">
          <img :src="scope.row.image" alt="员工头像" height="40px">
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="所属部门" width="120" align="center"/>
      <el-table-column prop="job" label="职位" width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.job==1">班主任</span>
          <span v-else-if="scope.row.job==2">讲师</span>
          <span v-else-if="scope.row.job==3">学工主管</span>
          <span v-else-if="scope.row.job==4">教研主管</span>
          <span v-else-if="scope.row.job==5">咨询师</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职日期" width="200" align="center"/>
      <el-table-column prop="updateTime" label="最后操作时间" width="300" align="center"/>
      <el-table-column  label="操作"  align="center" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="edit(scope.row.id)"><el-icon><Edit /></el-icon>编辑</el-button>
          <el-button type="danger" size="small" @click="deleteByID(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50,75,100]"
        :background="background"
        layout="total,sizes, prev, pager, next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!--  dialog-->
  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle">
    <el-form :model="emp" label-width="80px" :rules="rules" ref="formRef">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="emp.username" placeholder="请输入员工用户名，2-20个字"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="emp.name" placeholder="请输入员工姓名，2-10个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="emp.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="emp.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="emp.job" placeholder="请选择职位" style="width: 100%;">
              <el-option v-for="(item) in jobs" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="emp.salary" placeholder="请输入员工薪资"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="emp.deptId" placeholder="请选择部门" style="width: 100%;">
              <el-option v-for="(item) in depts" :key="item.id" :label=item.name :value=item.id></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="emp.entryDate" type="date" style="width: 100%;" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/upload"
                :headers="{'token':token}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="emp.image" :src="emp.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addExprItem">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row :gutter="3" v-for="(item,index) in emp.exprList" :key="index">
        <el-col :span="10">
          <el-form-item size="small"  label="时间" label-width="80px">
            <el-date-picker v-model="item.exprDate" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input placeholder="请输入公司名称" v-model="item.company"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input placeholder="请输入职位" v-model="item.job"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteExprItem">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
#search{
  margin:10px 0px;
}
#table-container{
  margin:10px auto
}
.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border-radius: 10px;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>